<template>
  <view class="container">
    <!-- 医生信息卡片 -->
    <view class="doctor-card">
      <view class="doctor-header">
        <view class="doctor-info">
          <view class="doctor-title">
            <text class="doctor-name">{{ doctorInfo.name }}</text>
            <text class="doctor-role">{{ doctorInfo.title }}</text>
          </view>
          <view class="doctor-department">
            <text>{{ doctorInfo.department }}</text>
            <van-icon name="arrow" />
          </view>
        </view>
        <view class="doctor-avatar">
          <image 
            :src="doctorInfo.avatar || '/static/logo.png'" 
            class="avatar-image"
            mode="aspectFill"
          />
          <!-- <view class="follow-btn">
            <van-icon name="like-o" color="#07c160" size="16" />
            <text class="follow-text">关注</text>
          </view> -->
        </view>
      </view>
      
      <!-- 医院信息 -->
      <view class="hospital-info">
        <van-tag type="primary" size="mini">{{ doctorInfo.titleLevel }}</van-tag>
        <text class="hospital-name">{{ doctorInfo.hospital }}</text>
      </view>
      
      <!-- 医生统计 -->
      <view class="doctor-stats">
        <view class="stat-item">
          <van-icon name="star" color="#ffc107" size="16" />
          <text class="stat-value">{{ doctorInfo.rating }}</text>
        </view>
        <view class="stat-item">
          <text class="stat-label">接诊数</text>
          <text class="stat-value">{{ doctorInfo.consultationCount }}</text>
        </view>
        <!-- <view class="stat-item">
          <text class="stat-label">关注数</text>
          <text class="stat-value">{{ doctorInfo.followCount }}</text>
        </view> -->
      </view>
      
      <!-- 擅长简介 -->
      <view class="speciality-section">
        <view class="section-header">
          <text class="section-title">擅长</text>
          <text class="section-subtitle">简介</text>
          <view class="more-btn">
            <text class="more-text">医生信息</text>
            <van-icon name="arrow" />
          </view>
        </view>
      </view>
    </view>
    
    <!-- 医生公告 -->
    <view class="notice-section">
      <view class="notice-header">
        <van-icon name="volume-o" color="#07c160" size="20" />
        <text class="notice-title">医生公告</text>
        <van-icon name="arrow" />
      </view>
      <view class="notice-content">
        <text>{{ doctorInfo.announcement || '暂无公告' }}</text>
      </view>
    </view>
    
    <!-- 预约挂号区域 -->
    <view class="appointment-section">
      <view class="appointment-header">
        <van-icon name="calendar-o" color="#4285f4" size="24" />
        <text class="appointment-title">预约挂号</text>
        <view class="price-info">
          <text class="price-label">￥{{ appointmentFee }}</text>
          <text class="price-unit">起</text>
        </view>
      </view>
      
      <!-- 院区选择 -->
      <view class="hospital-area">
        <view class="area-indicator"></view>
        <text class="area-name">{{ selectedArea }}</text>
      </view>
      
      <!-- 时间段列表 -->
      <view class="time-slots">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
          <van-loading color="#1989fa" size="24px">加载中...</van-loading>
        </view>
        
        <!-- 时间段列表 -->
        <view 
          v-else-if="availableTimeSlots.length > 0"
          v-for="slot in availableTimeSlots" 
          :key="slot.id"
          class="time-slot-item"
          :class="{ 
            disabled: slot.available === 0 || slot.status === 1,
            'stopped': slot.status === 1 
          }"
        >
          <!-- 添加余号状态标签 - 只在正常状态且余号较少但还有余号时显示 -->
          <view class="slot-status-badge" v-if="slot.status === 0 && slot.available <= 5 && slot.available > 0">
            <text 
              class="status-text"
              :class="{
                'urgent': slot.available <= 1,
                'low': slot.available <= 3 && slot.available > 1
              }"
            >
              仅剩${slot.available}个
            </text>
          </view>
          
          <!-- 原有的时间段内容 -->
          <view class="slot-content">
            <view class="slot-date">
              <text class="slot-day">{{ slot.date }}</text>
              <text class="slot-period">{{ slot.period }}</text>
            </view>
            <view class="slot-info">
              <text class="slot-type">{{ slot.type }}</text>
              <text class="slot-price">￥{{ slot.price }}</text>
              <!-- 添加余号信息显示 - 只在正常状态时显示 -->
              <view class="slot-remaining" v-if="slot.status === 0">
                <text class="remaining-label">余号：</text>
                <text 
                  class="remaining-count"
                  :class="{ 
                    'low-stock': slot.available <= 3 && slot.available > 0,
                    'no-stock': slot.available === 0 
                  }"
                >
                  {{ slot.available > 0 ? slot.available : '0' }}
                </text>
              </view>
            </view>
            <view class="slot-action">
              <van-button 
                v-if="slot.status === 0 && slot.available > 0"
                type="info" 
                size="small"
                @click="bookAppointment(slot)"
              >
                预约
              </van-button>
              <view v-else-if="slot.status === 1" class="stopped-badge">
                <text class="stopped-text">停诊</text>
              </view>
              <view v-else class="sold-out-badge">
                <text class="sold-out-text">约满</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 暂无数据 -->
        <view v-else class="no-data">
          <text>暂无可预约时间段</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useMedicalStore } from '@/stores/modules/medical'
import { useMessageStore } from '@/stores/modules/message'
import { getClinicTimeSlots, createAppointment, type ClinicTimeSlot } from '@/api/appointment'
import { useUserStore } from '@/stores'
// 医生信息接口 后端就是staff
interface DoctorInfo {
  id: number
  name: string
  title: string
  department: string
  hospital: string
  titleLevel: string
  avatar: string
  rating: number
  consultationCount: number
  followCount: number
  announcement: string
}

// 时间段接口 
interface TimeSlot {
  id: string
  date: string
  period: string
  duration: string
  type: string
  price: number
  available: number
  status: number  // 添加状态字段：0-正常，1-停诊
  bookedAt: Date  // 预约时间
}

// Store实例
const medicalStore = useMedicalStore()
const messageStore = useMessageStore()

// 页面参数
const departmentId = ref('')
const departmentName = ref('')

// 医生信息
const doctorInfo = ref<DoctorInfo>({
  id: 1,
  name: '马玲',
  title: '护师',
  department: '风湿免疫科',
  hospital: '', // 改为空字符串，将从pinia获取
  titleLevel: '三级甲等',
  avatar: '',
  rating: 5,
  consultationCount: 1,
  followCount: 25,
  announcement: '暂无公告'
})

// 预约相关数据
const appointmentFee = ref(15)
const selectedArea = ref('')

// 可预约时间段
const availableTimeSlots = ref<TimeSlot[]>([
  {
    id: '1',
    date: '2025-08-18 周一 下午',
    period: '3天后',
    duration: '',
    type: '风湿科慢病管理',
    price: 15.00,
    available: 5,
    status: 0,  // 正常状态
    bookedAt: new Date('2025-08-18T14:00:00')
  },
  {
    id: '2',
    date: '2025-08-21 周四 下午',
    period: '6天后',
    duration: '',
    type: '风湿科慢病管理',
    price: 15.00,
    available: 3,
    status: 1,  // 停诊状态
    bookedAt: new Date('2025-08-21T14:00:00')
  }
])

// 预约挂号
const bookAppointment = async (slot: TimeSlot) => {
  const userStore = useUserStore()
  try {
    // 从store获取当前选中的就诊卡
    const currentCard = medicalStore.getCurrentMedicalCard()
    
    if (!currentCard) {
      uni.showToast({
        title: '请先选择就诊卡',
        icon: 'none'
      })
      uni.navigateTo({
        url: '/pages/appointment/medical-card-select'
      })
      return
    }

    // 显示加载状态
    uni.showLoading({
      title: '预约中...'
    })

    // 调用后端预约接口
    const appointmentParams = {
      staffId: doctorInfo.value.id,           // 医生id
      patientId: currentCard.id, 
      patientName:currentCard.patientName,                        // 患者id（这里先模拟为1）
      typeId: 1,                             // 预约挂号是1
      userId: userStore.userInfo.userId,                             // 用户id（先模拟是2）
      clnicId: slot.id,            // 坐诊id
      bookedAt: new Date(slot.bookedAt.getTime() + 8 * 60 * 60 * 1000).toISOString().replace('T', ' ').split('.')[0]  // 转换为北京时间 GMT+8
    }
    console.log("预约请求",appointmentParams)
    const response = await createAppointment(appointmentParams)
    
    // 隐藏加载状态
    uni.hideLoading()

    if (response.code === 200) {
      // 预约成功，使用后端返回的数据
      const appointmentData = response.data

        // 生成本地预约记录用于store管理
        const localAppointmentData = {
        orderNo: appointmentData.orderId,
        department: departmentName.value,
        departmentId: departmentId.value,
        doctorName: doctorInfo.value.name,
        doctorId: doctorInfo.value.id.toString(),
        date: slot.date.split(' ')[0],
        time: slot.period,
        fee: slot.price,
        status: '待支付' as const,
        notes: `患者：${currentCard.patientName}，预约类型：${slot.type}`,
        appointmentId: appointmentData.id,
        slotNo: appointmentData.slotNo,
        clnicId: appointmentParams.clnicId  // 添加医生坐诊ID
      }
        // 添加到医疗记录store
        const newAppointment = medicalStore.setCurrentAppointment(localAppointmentData)
console.log('当前预约:', newAppointment)

// 如不需要，可保留或删除消息创建
// messageStore.createAppointmentMessage(newAppointment, 'created')
      // 创建预约成功消息
      messageStore.createAppointmentMessage(newAppointment, 'created')

    
      
      // 显示成功提示
      uni.showToast({
        title: '预约成功',
        icon: 'success',
        duration: 2000
      })

      // 延迟跳转到待支付页面，传递完整参数
      setTimeout(() => {
        // 格式化日期用于显示
        const dateObj = new Date(slot.date.split(' ')[0])
        const formattedDate = `${String(dateObj.getMonth() + 1).padStart(2, '0')}月${String(dateObj.getDate()).padStart(2, '0')}日 ${['周日', '周一', '周二', '周三', '周四', '周五', '周六'][dateObj.getDay()]}`
        
        // 简化跳转参数，主要从pinia store获取数据
        const params = [
          `orderNo=${encodeURIComponent(appointmentData.orderId)}`,
          `appointmentId=${encodeURIComponent(appointmentData.id)}`
        ].join('&')
        
        uni.navigateTo({
          url: `/pages/appointment/pending-payment?${params}`
        })
      }, 2000)
    } else {
      // 预约失败
      uni.showToast({
        title: response.msg || '预约失败',
        icon: 'none'
      })
    }
    
  } catch (error) {
    // 隐藏加载状态
    uni.hideLoading()
    
    console.error('预约失败:', error)
    uni.showToast({
      title: '预约失败，请重试',
      icon: 'none'
    })
  }
}

// 添加加载状态
const loading = ref(false)

// 数据转换函数 - 将接口数据转换为页面显示格式
const convertClinicDataToTimeSlots = (clinicData: ClinicTimeSlot[]): TimeSlot[] => {
  return clinicData.map(item => {
    // 转换日期格式 - 处理 "2025-08-20 09:00:00" 格式
    const date = new Date(item.clnicTime)
    const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
    
    // 计算剩余号源
    const available = item.slotTotal - item.slotUse
    return {
      id: item.id,
      date: `${dateStr} ${weekDay} ${item.period}`,
      period: `${Math.ceil((date.getTime() - Date.now()) / (1000 * 60 * 60 * 24))}天后`,
      duration: '',
      type: doctorInfo.value.department + '门诊',
      price: appointmentFee.value,
      available: available,
      status: item.status,  // 添加状态字段
      bookedAt: new Date(item.clnicTime)  // 直接使用后端返回的完整时间
    }
  })
}

// 加载医生预约时间段数据
const loadDoctorTimeSlots = async () => {
  if (!doctorInfo.value.id) {
    console.log('医生ID为空，无法加载时间段')
    return
  }
  
  try {
    loading.value = true
    console.log('正在请求医生时间段，医生ID:', doctorInfo.value.id)
    const response = await getClinicTimeSlots(doctorInfo.value.id.toString())
    console.log('医生时间段接口响应:', response)
    
    if (response.code === 200 && response.data) {
      // 转换数据格式并更新时间段列表
      availableTimeSlots.value = convertClinicDataToTimeSlots(response.data)
      console.log('转换后的时间段数据:', availableTimeSlots.value)
    } else {
      console.log('接口返回失败:', response)
      uni.showToast({
        title: response.msg || '获取预约时间失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取预约时间段失败:', error)
    uni.showToast({
      title: '获取预约时间失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 新增：从pinia获取医院信息的方法
const loadHospitalInfo = () => {
  const currentHospital = medicalStore.getCurrentHospital();
  if (currentHospital) {
    doctorInfo.value.hospital = currentHospital.deptName;
    selectedArea.value = currentHospital.deptName; // 假设院区名称就是医院名称
    console.log('从pinia获取医院信息:', currentHospital);
  } else {
    console.log('pinia中没有医院信息，使用默认值');
    doctorInfo.value.hospital = '未选择医院';
    selectedArea.value = '未选择院区';
  }
};

// 修改 onLoad 函数，在页面加载时获取实际数据
onLoad(async (options: Record<string, string>) => {
  console.log('医生预约页面 onLoad', options)
  
  departmentId.value = options.departmentId || '26'
  departmentName.value = options.departmentName || '风湿免疫科'
  
  // 如果传入了医生信息，更新医生数据
  if (options.doctorId) {
    doctorInfo.value.id = parseInt(options.doctorId)
  }
  if (options.doctorName) {
    doctorInfo.value.name = options.doctorName
  }
  if (options.department) {
    doctorInfo.value.department = options.department
  }
  
  // 新增：从pinia加载医院信息
  loadHospitalInfo();
  
  // 检查当前是否有选中的就诊卡
  const currentCard = medicalStore.getCurrentMedicalCard()
  console.log('当前就诊卡信息:', currentCard)
  
  // 加载医生预约时间段
  await loadDoctorTimeSlots()
})
</script>

<style lang="scss" scoped>
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 40rpx;
}

.doctor-card {
  background: white;
  margin: 24rpx;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.doctor-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24rpx;
}

.doctor-info {
  flex: 1;
}

.doctor-title {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 12rpx;
}

.doctor-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #323233;
}

.doctor-role {
  font-size: 28rpx;
  color: #646566;
}

.doctor-department {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 28rpx;
  color: #969799;
}

.doctor-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
}

.avatar-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #f7f8fa;
}

.follow-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 24rpx;
  color: #07c160;
}

.hospital-info {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.hospital-name {
  font-size: 28rpx;
  color: #323233;
}

.doctor-stats {
  display: flex;
  align-items: center;
  gap: 32rpx;
  margin-bottom: 24rpx;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 28rpx;
}

.stat-label {
  color: #646566;
}

.stat-value {
  color: #323233;
  font-weight: 500;
}

.speciality-section {
  .section-header {
    display: flex;
    align-items: center;
    gap: 16rpx;
  }
  
  .section-title {
    font-size: 28rpx;
    color: #07c160;
    font-weight: 500;
  }
  
  .section-subtitle {
    font-size: 28rpx;
    color: #323233;
  }
  
  .more-btn {
    margin-left: auto;
    display: flex;
    align-items: center;
    gap: 8rpx;
    font-size: 28rpx;
    color: #07c160;
  }
}

.notice-section {
  background: white;
  margin: 0 24rpx 24rpx;
  border-radius: 16rpx;
  padding: 32rpx;
}

.notice-header {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.notice-title {
  flex: 1;
  font-size: 32rpx;
  font-weight: 500;
  color: #323233;
}

.notice-content {
  font-size: 28rpx;
  color: #646566;
  line-height: 1.6;
}

.appointment-section {
  background: white;
  margin: 0 24rpx;
  border-radius: 16rpx;
  padding: 32rpx;
}

.appointment-header {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.appointment-title {
  flex: 1;
  font-size: 32rpx;
  font-weight: 500;
  color: #323233;
}

.price-info {
  display: flex;
  align-items: baseline;
  gap: 4rpx;
}

.price-label {
  font-size: 32rpx;
  font-weight: bold;
  color: #ee0a24;
}

.price-unit {
  font-size: 24rpx;
  color: #969799;
}

.hospital-area {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 32rpx;
}

.area-indicator {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background-color: #ee0a24;
}

.area-name {
  font-size: 28rpx;
  color: #323233;
}

.time-slots {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60rpx 0;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60rpx 0;
  color: #969799;
  font-size: 28rpx;
}

.time-slot-item {
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 24rpx;
  background-color: #f7f8fa;
  border-radius: 12rpx;
  
  &.disabled {
    opacity: 0.5;
  }
  
  &.stopped {
    background-color: #f5f5f5;
    border: 2rpx solid #d3d3d3;
  }
}

.slot-status-badge {
  position: absolute;
  top: -8rpx;
  right: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  background-color: #07c160;
  z-index: 1;
  
  .status-text {
    font-size: 20rpx;
    color: white;
    font-weight: 500;
    
    &.urgent {
      background-color: #ee0a24;
    }
    
    &.low {
      background-color: #ff976a;
    }
    
    &.stopped {
      background-color: #969799;
    }
  }
}

.slot-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.slot-date {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.slot-day {
  font-size: 28rpx;
  color: #323233;
  font-weight: 500;
}

.slot-period {
  font-size: 24rpx;
  color: #969799;
}

.slot-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  margin: 0 32rpx;
}

.slot-type {
  font-size: 24rpx;
  color: #646566;
}

.slot-price {
  font-size: 28rpx;
  color: #ee0a24;
  font-weight: 500;
}

// 新增余号信息样式
.slot-remaining {
  display: flex;
  align-items: center;
  gap: 4rpx;
  margin-top: 4rpx;
}

.remaining-label {
  font-size: 22rpx;
  color: #969799;
}

.remaining-count {
  font-size: 24rpx;
  font-weight: 500;
  color: #07c160;
  
  &.low-stock {
    color: #ff976a; // 橙色 - 余号较少时
  }
  
  &.no-stock {
    color: #ee0a24; // 红色 - 无余号时
  }
}

.slot-action {
  min-width: 120rpx;
  
  .sold-out-badge {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 12rpx 24rpx;
    background-color: #f7f8fa;
    border-radius: 8rpx;
    border: 2rpx solid #ebedf0;
  }
  
  .sold-out-text {
    font-size: 24rpx;
    color: #969799;
  }

  .stopped-badge {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 12rpx 24rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    border: 2rpx solid #d3d3d3;
  }

  .stopped-text {
    font-size: 24rpx;
    color: #969799;
  }
}
</style>
